package ruc.MongoDB;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

public class MongoDB_Common {
    public static MongoDatabase GetMongoDB(String IP, int port, String dbName) {
        MongoDatabase mongoDatabase = null;
        try {

            MongoClient mongoClient = new MongoClient(IP, port);
            mongoDatabase = mongoClient.getDatabase(dbName);

            System.out.printf("[TSBench-D] >>>>>> Connect to mongoDB successfully >>>>>\n");
        }catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }

        return mongoDatabase;
    }

    public static MongoCollection<Document> GetMongoCollection(String IP, int port, String dbName, String tbName) {
        MongoCollection<Document> collection = null;
        try {
            // 连接到数据库
            MongoDatabase mongoDatabase = GetMongoDB(IP, port, dbName);

            collection = mongoDatabase.getCollection(tbName);

            System.out.printf("[TSBench-D] >>>>>> Get Mongo Collection successfully >>>>>\n");
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }

        return collection;
    }

    public static void main(String[] args) {
        MongoCollection<Document> documentMongoCollection = MongoDB_Common.GetMongoCollection("124.71.232.37", 27017, "db", "d1");
        documentMongoCollection.insertOne(new Document().append("name", "zhd"));
    }
}
